package com.future.direction;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.support.annotation.RequiresApi;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.blankj.utilcode.util.Utils;
import com.future.direction.common.util.LocaleUtils;
import com.future.direction.di.module.AppModule;
import com.liulishuo.filedownloader.FileDownloader;
import com.future.direction.common.Constant;
import com.future.direction.common.MyActivityManager;
import com.future.direction.common.util.AppCrashHandlerUtil;
import com.future.direction.common.util.LogUtil;
import com.future.direction.di.component.AppComponent;
import com.future.direction.di.component.DaggerAppComponent;
import com.future.direction.di.module.HttpModule;
import com.future.direction.interfaces.ForegroundCallbacks;
import com.future.direction.jpush.JpushUtil;

import java.util.List;
import java.util.Locale;

/**
 * Created by zhangpeng on 2017/11/20.
 */

public class App extends MultiDexApplication {
    //环境 1:线下环境 2:线上测试 3:正式环境
    public static final int FORMAL_ENVIRONMENT = Constant.IS_RELEASE ? 3 : 1;
    public static boolean LogFlag;
    public static boolean LogCrashFile;

    private static App mContext;

    public static Activity mForegroundActivity;

    private static Handler mMainHandler;

    private static Thread mMainThread;

    private static int mMainThreadId;

    private static Looper mMainThreadLooper;

    private AppComponent mAppComponent;

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onCreate() {
        super.onCreate();
        FileDownloader.setupOnApplicationOnCreate(this);
        MultiDex.install(this);
        mAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this))
                .httpModule(new HttpModule()).build();
        switch (FORMAL_ENVIRONMENT) {
            case 1:
                //线下
            case 2:
                //线上测试
                LogFlag = true;
                break;
            case 3:
                //正式
                LogFlag = false;
                break;
        }

        mContext = (App) getApplicationContext();
        mMainHandler = new Handler();
        mMainThread = Thread.currentThread();
        mMainThreadId = android.os.Process.myTid();
        mMainThreadLooper = getMainLooper();
        JpushUtil.init();
        Utils.init(this);
        App.LogCrashFile = true;
        AppCrashHandlerUtil.getInstance().init(this);
        //7.0系统通过uri访问时设置，防止文件不能访问
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        initAppStatusListener();
        getStatus();
    }

    private void getStatus() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                MyActivityManager.getInstance().setCurrentActivity(activity);

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void initAppStatusListener() {
        ForegroundCallbacks.init(this).addListener(new ForegroundCallbacks.Listener() {
            @Override
            public void onBecameForeground() {
                LogUtil.d("BACK", "应用回到前台调用重连方法");
            }

            @Override
            public void onBecameBackground() {

            }
        });
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Locale _UserLocale = LocaleUtils.getUserLocale(this);
        //系统语言改变了应用保持之前设置的语言
        if (_UserLocale != null) {
            Locale.setDefault(_UserLocale);
            Configuration _Configuration = new Configuration(newConfig);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                _Configuration.setLocale(_UserLocale);
            } else {
                _Configuration.locale = _UserLocale;
            }
            getResources().updateConfiguration(_Configuration, getResources().getDisplayMetrics());
        }
    }

    /**
     * 获取全局上下文
     *
     * @return
     */
    public static App getApplication() {
        return mContext;
    }

    /**
     * 获取主线程handler
     *
     * @return
     */
    public static Handler getMainThreadHandler() {
        return mMainHandler;
    }

    /**
     * 获取主线程
     *
     * @return
     */
    public static Thread getMainThread() {
        return mMainThread;
    }

    /**
     * 获取主线程id
     *
     * @return
     */
    public static int getMainThreadId() {
        return mMainThreadId;
    }

    /**
     * 获取主线程轮询器
     *
     * @return
     */
    public static Looper getMainThreadLooper() {
        return mMainThreadLooper;
    }


    public static Activity getmForegroundActivity() {
        return mForegroundActivity;
    }

    public static void setmForegroundActivity(Activity mForegroundActivity) {
        App.mForegroundActivity = mForegroundActivity;
    }

    // 获取清单文件的metaData
    private String getMetaDataValue(String key) {
        try {
            ApplicationInfo info = getPackageManager().getApplicationInfo(
                    getPackageName(), PackageManager.GET_META_DATA);
            return info.metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public static boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getApplicationContext().getSystemService(
                        Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public AppComponent getAppComponent() {

        return mAppComponent;
    }
}
